package com.example.teemor.es_demo.service;

import com.example.teemor.es_demo.dto.PageResponse;
import com.example.teemor.es_demo.entity.ServiceLog;
import com.example.teemor.es_demo.entity.UserBehavior;
import com.example.teemor.es_demo.repository.clickhouse.LogRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 日志管理服务
 * 提供统一的日志查询和管理接口
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LogManagementService {
    
    private final LogRepository logRepository;
    
    /**
     * 分页查询服务日志
     * 
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param keyword 关键词
     * @param level 日志级别
     * @param page 页码（从0开始）
     * @param size 每页大小
     * @return 分页结果
     */
    public PageResponse<ServiceLog> queryServiceLogs(String startTime, String endTime, 
                                                    String keyword, String level, 
                                                    int page, int size) {
        try {
            // 查询数据
            List<ServiceLog> logs = logRepository.queryServiceLogs(startTime, endTime, keyword, level, page, size);
            
            // 查询总数
            long total = logRepository.countServiceLogs(startTime, endTime, keyword, level);
            
            // 计算总页数
            int totalPages = (int) Math.ceil((double) total / size);
            
            return PageResponse.<ServiceLog>builder()
                    .content(logs)
                    .page(page)
                    .size(size)
                    .totalElements(total)
                    .totalPages(totalPages)
                    .first(page == 0)
                    .last(page >= totalPages - 1)
                    .build();
                    
        } catch (Exception e) {
            log.error("查询服务日志失败", e);
            throw new RuntimeException("查询服务日志失败", e);
        }
    }
    
    /**
     * 分页查询用户行为日志
     * 
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param keyword 关键词
     * @param page 页码（从0开始）
     * @param size 每页大小
     * @return 分页结果
     */
    public PageResponse<UserBehavior> queryUserBehaviors(String startTime, String endTime, 
                                                        String keyword, int page, int size) {
        try {
            // 查询数据
            List<UserBehavior> behaviors = logRepository.queryUserBehaviors(startTime, endTime, keyword, page, size);
            
            // 查询总数
            long total = logRepository.countUserBehaviors(startTime, endTime, keyword);
            
            // 计算总页数
            int totalPages = (int) Math.ceil((double) total / size);
            
            return PageResponse.<UserBehavior>builder()
                    .content(behaviors)
                    .page(page)
                    .size(size)
                    .totalElements(total)
                    .totalPages(totalPages)
                    .first(page == 0)
                    .last(page >= totalPages - 1)
                    .build();
                    
        } catch (Exception e) {
            log.error("查询用户行为日志失败", e);
            throw new RuntimeException("查询用户行为日志失败", e);
        }
    }
    
    /**
     * 获取服务日志统计信息
     */
    public ServiceLogStats getServiceLogStats(String startTime, String endTime) {
        try {
            long totalCount = logRepository.countServiceLogs(startTime, endTime, null, null);
            long errorCount = logRepository.countServiceLogs(startTime, endTime, null, "ERROR");
            long warnCount = logRepository.countServiceLogs(startTime, endTime, null, "WARN");
            long infoCount = logRepository.countServiceLogs(startTime, endTime, null, "INFO");
            long debugCount = logRepository.countServiceLogs(startTime, endTime, null, "DEBUG");
            
            return ServiceLogStats.builder()
                    .totalCount(totalCount)
                    .errorCount(errorCount)
                    .warnCount(warnCount)
                    .infoCount(infoCount)
                    .debugCount(debugCount)
                    .build();
                    
        } catch (Exception e) {
            log.error("获取服务日志统计信息失败", e);
            throw new RuntimeException("获取服务日志统计信息失败", e);
        }
    }
    
    /**
     * 获取用户行为日志统计信息
     */
    public UserBehaviorStats getUserBehaviorStats(String startTime, String endTime) {
        try {
            long totalCount = logRepository.countUserBehaviors(startTime, endTime, null);
            
            return UserBehaviorStats.builder()
                    .totalCount(totalCount)
                    .build();
                    
        } catch (Exception e) {
            log.error("获取用户行为日志统计信息失败", e);
            throw new RuntimeException("获取用户行为日志统计信息失败", e);
        }
    }
    
    /**
     * 服务日志统计信息
     */
    public static class ServiceLogStats {
        private long totalCount;
        private long errorCount;
        private long warnCount;
        private long infoCount;
        private long debugCount;
        
        public static ServiceLogStatsBuilder builder() {
            return new ServiceLogStatsBuilder();
        }
        
        public static class ServiceLogStatsBuilder {
            private long totalCount;
            private long errorCount;
            private long warnCount;
            private long infoCount;
            private long debugCount;
            
            public ServiceLogStatsBuilder totalCount(long totalCount) {
                this.totalCount = totalCount;
                return this;
            }
            
            public ServiceLogStatsBuilder errorCount(long errorCount) {
                this.errorCount = errorCount;
                return this;
            }
            
            public ServiceLogStatsBuilder warnCount(long warnCount) {
                this.warnCount = warnCount;
                return this;
            }
            
            public ServiceLogStatsBuilder infoCount(long infoCount) {
                this.infoCount = infoCount;
                return this;
            }
            
            public ServiceLogStatsBuilder debugCount(long debugCount) {
                this.debugCount = debugCount;
                return this;
            }
            
            public ServiceLogStats build() {
                ServiceLogStats stats = new ServiceLogStats();
                stats.totalCount = this.totalCount;
                stats.errorCount = this.errorCount;
                stats.warnCount = this.warnCount;
                stats.infoCount = this.infoCount;
                stats.debugCount = this.debugCount;
                return stats;
            }
        }
        
        // Getters
        public long getTotalCount() { return totalCount; }
        public long getErrorCount() { return errorCount; }
        public long getWarnCount() { return warnCount; }
        public long getInfoCount() { return infoCount; }
        public long getDebugCount() { return debugCount; }
    }
    
    /**
     * 用户行为日志统计信息
     */
    public static class UserBehaviorStats {
        private long totalCount;
        
        public static UserBehaviorStatsBuilder builder() {
            return new UserBehaviorStatsBuilder();
        }
        
        public static class UserBehaviorStatsBuilder {
            private long totalCount;
            
            public UserBehaviorStatsBuilder totalCount(long totalCount) {
                this.totalCount = totalCount;
                return this;
            }
            
            public UserBehaviorStats build() {
                UserBehaviorStats stats = new UserBehaviorStats();
                stats.totalCount = this.totalCount;
                return stats;
            }
        }
        
        // Getter
        public long getTotalCount() { return totalCount; }
    }
}